package com.thousandsunny;

import com.thousandsunny.consumer.MyOAuth2FeignRequestInterceptor;
import feign.RequestInterceptor;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.mvc.WebContentInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Savitar
 */
@EnableFeignClients
@SpringCloudApplication
@EnableScheduling
@EnableOAuth2Client
public class ConsumerApplication extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        new SpringApplicationBuilder(ConsumerApplication.class).web(true).run(args);
    }


    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor() {
        return new MyOAuth2FeignRequestInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new WebContentInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                MyOAuth2FeignRequestInterceptor.authenticationThreadLocal.set(authentication);
                return super.preHandle(request, response, handler);
            }
        }).addPathPatterns("/**");
    }

}
